package com.thinkwide.data.ormapping.sql;

import com.thinkwide.data.core.MFString;

public class MFSqlHelper {

    private String sql = "";

    private String select = "";
    private String where = "";
    private String orderby = "";
    private String groupby = "";

    public MFSqlHelper(String sql) {
        this.sql = sql;
        boolean find = false;

        String str = sql.toUpperCase();
        sql = sql.replace('\n', ' ');
        sql = sql.replace('\r', ' ');
        select = sql;

        int iWhere = str.indexOf(" WHERE ");
        int iOrder = str.indexOf(" ORDER ");
        int iGroup = str.indexOf(" GROUP ");
        if (iWhere > 0) {
            select = sql.substring(0, iWhere - 1);
            int iLength = iGroup > 0 ? iGroup : iOrder;
            if (iLength <= 0) {
                iLength = str.length();
            }

            where = sql.substring(iWhere, iLength);
            find = true;
        }


        if (iGroup > 0) {
            if (!find) {
                select = sql.substring(0, iGroup - 1);
            }

            int iLength = iOrder;
            if (iLength <= 0) {
                iLength = str.length();
            }

            groupby = sql.substring(iGroup, iLength);
            find = true;
        }

        if (iOrder > 0) {
            if (!find) {
                select = sql.substring(0, iOrder - 1);
            }
            int iLength = str.length();
            orderby = sql.substring(iOrder, iLength);
        }

    }

    @Override
    public String toString() {
        return select + " " + where + " " + groupby + " " + orderby;
    }

    public MFSqlHelper deleteWhere() {
        where = "";
        return this;
    }

    public MFSqlHelper addWhere(String value) {
        if (MFString.isNullOrEmpty(where)) {
            where = " WHERE " + value;
        } else {
            where = where + " and " + value;
        }
        return this;
    }

    public MFSqlHelper deleteOrderBy() {
        orderby = "";
        return this;
    }

    public MFSqlHelper addOrderBy(String value, String dir) {
        return addOrderBy(value + " " + dir);
    }

    public MFSqlHelper addOrderBy(String value) {
        if (MFString.isNullOrEmpty(orderby)) {
            orderby = " ORDER BY " + value;
        } else {
            orderby = orderby + "," + value;
        }
        return this;
    }

    public MFSqlHelper addGroupBy(String value) {
        if (MFString.isNullOrEmpty(groupby)) {
            groupby = " GROUP BY " + value;
        } else {
            groupby = groupby + "," + value;
        }
        return this;
    }

    public MFSqlHelper deleteGroupBy() {
        groupby = "";
        return this;
    }
}
